/*
把一个目录下的所有.txt文件合一个大的.txt文件，再对这个大文件进行压缩
*/

package main

import (
	"compress/zlib"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func copyTxt(filePath string, writer *zlib.Writer) error {
	// bs, err := ioutil.ReadFile(filePath)
	// if err != nil {
	// 	return fmt.Errorf("read file %s failed! err: %v", filePath, err)
	// }

	// _, err = writer.Write(bs)
	// if err != nil {
	// 	return fmt.Errorf("write file failed! err: %v", err)
	// }
	// return nil

	fileObj, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("read file %s failed! err: %v", filePath, err)
	}
	defer fileObj.Close()
	_, err = io.Copy(writer, fileObj)
	if err != nil {
		return fmt.Errorf("copy filepath %s content to zlib.writer failed! err: %v", filePath, err)
	}
	return nil
}

func getTxt(path string, outputFile string) error {
	fileInfos, err := ioutil.ReadDir(path)

	if err != nil {
		return fmt.Errorf("read path error! err: %v", err)
	}

	fileObj, err := os.OpenFile(outputFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0755)
	if err != nil {
		return fmt.Errorf("open outputfile %s failed! err: %v", outputFile, err)
	}

	defer fileObj.Close()

	zWriter := zlib.NewWriter(fileObj)

	for _, fileInfo := range fileInfos {
		if fileInfo.IsDir() {
			continue
		} else if strings.HasSuffix(fileInfo.Name(), ".txt") {
			filePath := filepath.Join(path, fileInfo.Name())
			err = copyTxt(filePath, zWriter)
			if err != nil {
				return err
			}
		}
	}
	zWriter.Flush()
	return nil
}

func main() {
	err := getTxt("./test1", "./compress.zlib")
	if err != nil {
		fmt.Println(err)
		return
	}

	file, _ := os.Open("./compress.zlib")
	reader, _ := zlib.NewReader(file)
	io.Copy(os.Stdout, reader)
}
